package com.ay.demo.guava.eventbus;

import java.util.concurrent.TimeUnit;

import com.ay.demo.guava.eventbus.event.AllowConcurrentEvent;
import com.ay.demo.guava.eventbus.event.AsynEvent;
import com.ay.demo.guava.eventbus.event.SyncEvent;

/**
 * <pre>
 * 1.对于EventBus在一个线程中处理,AsyncEventBus是异步处理的,即在一个线程池中处理.
 * 2.给订阅者加注解{@code AllowConcurrentEvents},是表示订阅者是线程安全的,使用的是EventSubscriber,不加此注解使用的是SynhcronizedEventBus.
 * </pre>
 * @author win7
 */
public class EventBusDemo {

	public static void main(String[] args) {
		// 测试线程安全的问题
//		testConcurrent();
		testAnnotation();
	}

	/**
	 * 测试注解{@code AllowConcurrentEvents}的作用
	 */
	private static void testAnnotation() {
		EventBusPublisher.getInstance().postEvent(new AllowConcurrentEvent(1000));
	}

	/**
	 * 测试线程安全的问题
	 */
	static void testConcurrent() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					EventBusPublisher.getInstance().postEvent(new SyncEvent(i));
					try {
						TimeUnit.MILLISECONDS.sleep(2);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					EventBusPublisher.getInstance().postEvent(new AsynEvent(i));
					try {
						TimeUnit.MILLISECONDS.sleep(3);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
